package cn.edu.hfut.dmic.webcollector.net;



import java.util.List;
import java.util.Map;

import cn.edu.hfut.dmic.webcollector.util.CharsetDetector;

/**
 * Response的一种实现，WebCollector默认使用HttpResponse作为http响应
 * @author hu
 */
public class HttpResponse{

    private String url;
    private int code;
    private Map<String,List<String>> headers=null;
    private byte[] content=null;
    private boolean redirect=false;
    private String realUrl=null;
    
    /**
     * 获取编码
     * @return
     */
    public String getCharset() {
    	String set = CharsetDetector.guessEncoding(getContent());
    	String contentType = getContentType();
    	if(contentType == null || "".equals(contentType)){
    		return set;
    	}else{
    		String[] tmp = contentType.split("; ");
        	for(int i = 0,len = tmp.length;i < len;i++){
        		if(tmp[i].startsWith("charset")){
        			set = tmp[i].substring(tmp[i].indexOf("=") + 1);
        			break;
        		}
        	}
        	return set;
    	}
	}

	public HttpResponse(String url){
        this.url=url;
    }

	public String getUrl() {
        return url;
    }
    
    public void setUrl(String url) {
        this.url = url;
    }
    public int getCode() {
        return code;
    }
    public List<String> getHeader(String name) {
        return headers.get(name);
    }
    public byte[] getContent() {
        return content;
    }
    
    public void setContent(byte[] content) {
        this.content = content;
    }
    public void setCode(int code) {
        this.code = code;
    }
    public Map<String, List<String>> getHeaders() {
        return headers;
    }
    public void setHeaders(Map<String, List<String>> headers) {
        this.headers=headers;
    }
    public String getContentType() {
        try{
        String contentType;
        List<String> contentTypeList = getHeader("Content-Type");
        if (contentTypeList == null) {
            contentType = null;
        } else {
            contentType = contentTypeList.get(0);
        }
            return contentType;
        }catch(Exception ex){
            return null;
        }
    }
    public boolean getRedirect() {
        return redirect;
    }
    public void setRedirect(boolean redirect) {
        this.redirect = redirect;
    }

	public String getRealUrl() {
		if (realUrl == null) {
            return url;
        }
        return realUrl;
    }
    public void setRealUrl(String realUrl) {
        this.realUrl = realUrl;
    }
}
